<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能回复</title>
    <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
    <link href="../css/styles.css" type="text/css" rel="stylesheet" media="all">
</head>
<body>
<div class="chat-container">
    <div class="chat-header">
        AI 智能解答
    </div>
    <div class="chat-body">
        <div class="chat-message received">
            欢迎使用 AI 智能工具，有什么可以帮助您的吗？
        </div>
    </div>
    <div class="chat-footer">
        <div class="input-container">
            <input type="text" id="messageInput" placeholder="输入消息...">
            <button id="sendButton">发送</button>
        </div>
        <div class="file-upload">
            <input type="file" id="fileInput">
            <label for="fileInput"></label>
        </div>
    </div>
</div>
<script>
    document.getElementById('sendButton').addEventListener('click', async function() {
        let input = document.getElementById('messageInput');
        let message = input.value;
        if (message.trim()!== '') {
            let chatBody = document.querySelector('.chat-body');
            let newMessage = document.createElement('div');
            newMessage.classList.add('chat-message','sent');
            newMessage.textContent = message;
            chatBody.appendChild(newMessage);
            input.value = '';
            try {
                let reply = await getAIReply(message);
                let replyMessage = document.createElement('div');
                replyMessage.classList.add('chat-message','received');
                replyMessage.textContent = reply;
                chatBody.appendChild(replyMessage);
            } catch (error) {
                console.error('Error getting AI reply:', error);
                let errorMessage = document.createElement('div');
                errorMessage.classList.add('chat-message','received');
                errorMessage.textContent = '对不起，获取回复时出现错误。';
                chatBody.appendChild(errorMessage);
            }
        }
    });

    async function getAIReply(message) {
        // 百度的 API 地址，你需要根据实际情况修改
        let apiUrl = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completion';
        let apiKey = 'YOUR_BAIDU_API_KEY'; // 请将此替换为你的百度 API 密钥
        let secretKey = 'YOUR_BAIDU_SECRET_KEY'; // 请将此替换为你的百度 Secret 密钥

        // 生成访问令牌（access token），这里是一个示例函数，实际情况可能需要调用百度的认证服务
        let accessToken = await getBaiduAccessToken(apiKey, secretKey);

        try {
            let response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + accessToken
                },
                body: JSON.stringify({
                    "messages": [{"role": "user", "content": message}]
                })
            });
            let data = await response.json();
            // 这里需要根据百度的 API 响应结构提取回复信息，以下是一个示例，可能需要修改
            return data.result;
        } catch (error) {
            throw error;
        }
    }

    async function getBaiduAccessToken(apiKey, secretKey) {
        // 此函数用于获取百度的访问令牌，这里是一个简单示例，可能需要根据百度的文档进行修改
        let tokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
        let response = await fetch(tokenUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `grant_type=client_credentials&client_id=${apiKey}&client_secret=${secretKey}`
        });
        let data = await response.json();
        return data.access_token;
    }
    document.querySelector('.file-upload input[type="file"]').addEventListener('change', function(event) {
        let file = event.target.files[0];
        if (file) {
            console.log('上传的文件:', file);
            // 这里可以添加文件上传的逻辑，例如使用 FormData 和 fetch 上传文件
        }
    });
</script>
</body>
</html>